<template>
  <n-upload
      v-bind="$attrs"
      action="http://localhost:8031/api/upload"
      v-model:file-list="state.fileList"
      list-type="image-card"
      @preview="handlePreview"
      @finish="handleFinish"
  />
  <n-modal
      v-model:show="showModal"
      preset="card"
      style="width: 600px"
      title="一张很酷的图片"
  >
    <img :src="previewImageUrl" style="width: 100%">
  </n-modal>
</template>

<script setup>
import {ref} from "vue";

defineOptions({name: 'ImgUpload'})

const props = defineProps({
  value: {
    type: [Array, String],
    default: () => ([])
  },
})

const emit = defineEmits(['update:value'])

const showModal = ref(false);
const previewImageUrl = ref("");

const uploadUrl = import.meta.env.VITE_BASE_API + "/upload"

function handlePreview(file) {
  const {url} = file;
  previewImageUrl.value = url;
  showModal.value = true;
}

const state = reactive({
  propsValue: props.value,
  fileList: [
    // { // 失败
    //   id: "a",
    //   name: "我是上传出错的普通文件.png",
    //   status: "error"
    // },
    // { // 成功
    //   id: "b",
    //   name: "我是普通文本.doc",
    //   status: "finished",
    //   type: "text/plain"
    // },
    // {
    //   id: "c",
    //   name: "我是自带url的图片.png",
    //   status: "finished",
    //   url: "https://07akioni.oss-cn-beijing.aliyuncs.com/07akioni.jpeg"
    // },
    // {
    //   id: "d",
    //   name: "我是上传进度99%的文本.doc",
    //   status: "uploading",
    //   percentage: 99
    // }
  ],
  previewFileList: []
})

const genFileList = (value = []) => {
  return value.map((item, index) => {
    return {
      id: index,
      name: item,
      status: "finished",
      url: item
    }
  }).filter((item) => item.url)
}
//
// watch(props, (newValue, olaValue) => {
//   console.log(newValue, olaValue, typeof newValue)
//   if (newValue !== olaValue) {
//     let _fileList = []
//     if (typeof newValue[0] === 'string') {
//       _fileList = genFileList(newValue[0].split(','))
//     } else if (newValue[0] instanceof Array) {
//       _fileList = genFileList(newValue[0])
//     } else {
//       console.error("图片组件，传递类型错误，请传递 string 或 Array 类型")
//     }
//
//     state.fileList = [].concat(_fileList)
//   }
//
// }, {deep: true})

watchEffect(() => {
  let _fileList = []
  let _propsValue = props.value
  if (typeof _propsValue === 'string') {
    _fileList = genFileList(_propsValue.split(','))
  } else if (_propsValue instanceof Array) {
    _fileList = genFileList(_propsValue)
  } else {
    console.error("图片组件，传递类型错误，请传递 string 或 Array 类型")
  }

  state.fileList = [].concat(_fileList)
})


const updateValue = (value = []) => {
  console.log('更新值:', value)
  if (typeof props.value === 'string') {
    emit('update:value', value.join(","))
  } else if (props.value instanceof Array) {
    emit('update:value', value.map((item) => item.url))
  }
}

const handleFinish = ({file, event}) => {
  // console.log(file, event);
  const res = JSON.parse((event?.target).response)
  // console.log(file, event, res);
  // 后端响应的信息
  // window.$message?.success((event?.target).response)
  const ext = file.name.split(".")[1];
  file.name = `更名.${ext}`;
  file.url = '';

  if (res.code !== 1) {
    window.$message?.success(res.message)
  } else {
    window.$message?.success(res.message)
    file.name = `更名.${ext}`;
    file.url = res.result.url;

    const fileList = state.fileList.concat({url: res.result.url}).filter((item) => item.url)
    updateValue([].concat(fileList))
  }

  return file;
};

</script>

<style scoped lang="scss">

</style>
